package xyz.mumuwei.youthcourseserver.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import xyz.mumuwei.youthcourseserver.common.lang.Const;
import xyz.mumuwei.youthcourseserver.intereptor.LoginInterceptor;

/**
 * @author Mumuwei
 * @date 2022/01/12 10:31
 */
@Slf4j
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {

    @Value("${projectPath}")
    private String projectPath;
    @Value("${filePath}")
    private String filePath;
    @Value("${avatarPath}")
    private String avatarPath;

    private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {
            "classpath:/META-INF/resources/", "classpath:/resources/",
            "classpath:/static/", "classpath:/public/" };

    /**
     * 拦截配置
     * @param registry 1
     */
    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginInterceptor())
                .addPathPatterns("/**")
                .excludePathPatterns(Const.EXCLUDE_PATH);
    }

    /**
     * 跨域请求配置
     * @param registry 1
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOriginPatterns("*")
                .allowedMethods("GET","PUT","POST","DELETE","OPTIONS")
                .allowCredentials(true)
                .maxAge(3600).allowedHeaders("*");
    }

    /**
     * 暴露静态文件
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/avatar/**")
                .addResourceLocations(projectPath + "/" + avatarPath + "/");
        registry.addResourceHandler("/static/**")
                .addResourceLocations(projectPath + "/" + filePath + "/");
        registry.addResourceHandler("/**")
                    .addResourceLocations(CLASSPATH_RESOURCE_LOCATIONS);
    }

}
